<?php
include_once '../../qc_base.php';
require_once('../../bootstrap.php');
require_once('../../lib/spyc/spyc.php');

function load_db_info_project($project_id){
	$q_proj = Doctrine_Query::create()
	->from('Projects p')
	->where('project_id = ?', $project_id);
	$results = $q_proj->execute();
	$project = $results->getFirst();


	load_db_info($project_id, $project->dbtype,$project->project_server,$project->project_db,$project->project_login,$project->project_pass);

}

function load_db_info($project_id, $engine = 'mysql',$host = '127.0.0.1',$db = 'sampledb',$user = 'root',$pass='',$port = '3306'){

	$dsn2 = $engine . ':' . '//' . $user . ':' . $pass . '@' . $host . ':' . $port . '/' . $db;
	$subdb = Doctrine_Manager::connection($dsn2,'subdb');

	Doctrine::generateYamlFromDb('subdbschema.yml', array('subdb'));

	$newyaml = new sfYamlParser();
	$ar_subdb_info = $newyaml->parse(file_get_contents('subdbschema.yml'));

	$manager = Doctrine_Manager::getInstance();
	$manager->setCurrentConnection('maindb');


	foreach($ar_subdb_info AS $table_class => $ar_table_info){
		$table_name = Doctrine_Inflector::tableize($table_class);
		$table_name = $ar_table_info['tableName'];
		$q_isthere = Doctrine_Query::create()
		->from('Tablesources ts') 
		->where('table_name = ?', $table_name)
		->andWhere('project_id = ?', $project_id);
		$doit = false;
		if($q_isthere->count() == 0){
	
			$newtable = new Tablesources();
			$newtable->table_name = $table_name;
			$newtable->project_id = $project_id;
			$newtable->table_alias = $table_name;
			$newtable->table_filter = 1;
			$newtable->save();
			$owner_table_id = $newtable->tablesource_id;
			$doit = true;
		}
		foreach($ar_table_info['columns'] AS $column_name => $ar_column_info){
			if($doit){
				$newvariable = new Variables();
				$newvariable->variable_name = $column_name;
				$newvariable->type = $ar_column_info['type'];
				if($ar_column_info['primary'] != 1){
					$is_key = 0;
				}else{
					$is_key = 1;
				}

				$newvariable->is_key = $is_key;
				$newvariable->source_id = $owner_table_id;
				$newvariable->project_id = $project_id;
				$newvariable->def_show_text = '';
				$newvariable->variable_size = get_size_from_type($ar_column_info['type']);
				$newvariable->save();
			}
		}
	}
}

function get_size_from_type($type, $defsize = 12){
	if(preg_match('/(^.+)\((.*)\)/', $type, $matches)){
		$rawtype = $matches[1];
		if(empty($matches[2])){
			return $defsize;
		}else{
			return $matches[2];
		}
	}else{
		$rawtype = $matches[1];
		return $defsize;
	}

}

?>

